package com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder;

import com.zebraphp.devtool.httpUtils.NetOkHttp.IOkHttp;
import com.zebraphp.devtool.util.ILog;
import com.zebraphp.devtool.httpUtils.NetOkHttp.callback.ICallback;
import com.zebraphp.devtool.httpUtils.NetOkHttp.responseHandler.BaseHandler;

import java.util.Map;

import okhttp3.Request;

/**
 * GET 请求体 构建
 */
public class GetBuilder extends BaseWithParamBuilder<GetBuilder> {

    public GetBuilder(IOkHttp IOkHttp) {
        super(IOkHttp);
    }

    @Override
    public void addTaskQueue(final BaseHandler responseParseHandler) {
        try {
            if(mUrl == null || mUrl.length() == 0) {
                throw new IllegalArgumentException("URL 地址 不能为空!!!");
            }

            if (mParams != null && mParams.size() > 0) {
                mUrl = putParamsToUrl(mUrl, mParams);
            }

            //调用的okHttp3构建器
            Request.Builder ok3Builder = new Request.Builder().url(mUrl).get();
            this.appendFinalHeadersToRequest(ok3Builder, mHeaders);

            if (mTag != null) {
                ok3Builder.tag(mTag);
            }

            //最终创建生成一个请求实体
            Request ok3Request = ok3Builder.build();

            mIOkHttp.getOkHttpClient().
                    newCall(ok3Request).//把请求实体加入到任务队列中
                    enqueue(new ICallback(responseParseHandler));

        } catch (Exception e) {
            ILog.printLib("Get enqueue error:" + e.getMessage());
            responseParseHandler.onError(0, e.getMessage());
        }

    }

    //生成带请求参数 的 GET URL
    private String putParamsToUrl(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append(url + "?");
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }

        sb = sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
